import { AxiosResponse } from 'axios'
import fs from 'fs-extra'
import path from 'path'

export const downloadFile = (result: AxiosResponse, outputDir = './') => {
  return new Promise<string>((resolve, reject) => {
    const contentDisposition =
      result.headers['content-disposition'] ??
      result.headers['Content-Disposition']
    const fileName =
      contentDisposition?.split('=')[1]?.replace(/"/g, '') ||
      new Date().getTime().toString()
    const filePath = path.resolve(outputDir, fileName)

    fs.ensureDirSync(path.dirname(filePath))
    const fileStream = fs.createWriteStream(filePath)
    result.data.pipe(fileStream)

    fileStream
      .on('close', () => {
        resolve(filePath)
      })
      .on('error', (error) => {
        reject(error)
      })
  })
}
